package com.wanlian.net.core;

import com.wanlian.netty.msg.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * Handles a client-side channel.
 */
public class DeviceClientHandler extends ChannelInboundHandlerAdapter { // (1)
    private Logger logger = LoggerFactory.getLogger(getClass());
    private final ByteBuf firstMessage;

    public DeviceClientHandler() {
        byte[] req = "Hello from client".getBytes();
        firstMessage = Unpooled.buffer(req.length);
        firstMessage.writeBytes(req);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // logger.info("client channel active");
        // logger.info("client send req...");
        // PingMsg pingMsg = new PingMsg();
        // PeerMsg peerMsg = new PeerMsg(pingMsg);
        // ctx.writeAndFlush(peerMsg);
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            PeerMsg peerMsg = (PeerMsg) msg;
            String msgType = peerMsg.getBaseMsg().getType();
            if (msgType.equals(MsgType.QUE_COUNT)) {
                QueCountMsg queCountMsg = (QueCountMsg) peerMsg.getBaseMsg();
                QueCountReplyMsg replyMsg = new QueCountReplyMsg();
                replyMsg.setTaskId(queCountMsg.getTaskId());
                replyMsg.setCount(PeerMsgQueue.size());
                PeerMsg psg = new PeerMsg(replyMsg);
                ctx.writeAndFlush(psg);
                System.out.println("Now I have:" + replyMsg.getCount());
            } else {
                PeerMsg copyMsg = peerMsg.deepCopyMsg();
                PeerMsgQueue.add(copyMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        // Close the connection when an exception is raised.
        logger.error("client caught exception", cause);
        ctx.close();
    }
}